import os
import socket
from time import sleep
import time
import sys

log_path = '/var/log/test.log'
port = 9987
def log(s):
    os.system(f"echo '{os.getpid()}|{port}: {time.time()}| {s}' >> {log_path}")
file = open(log_path,'a+')
sys.stdout = file
sys.stderr = file
pid = os.fork()
if pid!=0:
    exit(0)
os.setsid()
# os.chdir("/")
os.umask(0)
log('start')
# sleep(10)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
log("socket init")
s.bind(("127.0.0.1",port))
log('socket bind')
s.listen(5)
log('socket listen')
print("waiting for connection")
while True:
    log("start listening")
    sock, addr = s.accept()
    data = sock.recv(1000)
    _data = data.decode()
    log("accept connection,content"+_data)
    if data[0]==b'0'[0]:
        print("exit")
        exit()
    elif data[0]==b'1'[0]:
        print("echo!")
        print(f"Accept new connection from {addr}")
        sock.send(b'Hello '+data+b'!')
        log("info send")
    else:
        log(data[0])

os.system(f"echo 'end' >> {log_path}")